﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using QD.Snapshot.Core.Util;
using QD.Snapshot.Core.Config;

namespace QD.Snapshot.Core.BLL.File
{
    public class Snap
    {
        public static bool IsEmpty = false;

        /// <summary>
        /// 添加快照记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static int AddSnap(Model.Snap model)
        {
            int count = 0;
            model.state = 0;
            Model.Snap old = DAL.Snap.GetExists(model.keyword, model.userid, model.copyform, model.ranking, model.index_key, model.platform);
            if (old == null)
                count = DAL.Snap.Add(model);
            else
            {
                model.id = old.id;
                count = DAL.Snap.UpdateBySearch(model);
            }

            //更新新增平台数量  2018-04-18
            BLL.PromotionReport.InsertOrUpdateSnapshot(model);

            return count;
        }

        public static int GetCount()
        {
            return DAL.Snap.GetCountByMack(SiteConfig.UserId);
        }

        /// <summary>
        /// 获取即将生成HTML的快照结果
        /// </summary>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<int> GetListSnapByMack(int page,int pageSize = 10)
        {
            return DAL.Snap.GetListIdByMack(SiteConfig.Page, pageSize, SiteConfig.UserId);
        }


        public static void MackHTML(TextBox textBox)
        {
            //获取产品
            EchoHelper.ShowMessage(textBox, "[1/3]获取记录");

            var list = GetListSnapByMack(15);
            if (list == null)
            {
                IsEmpty = true;
                Echo(textBox, string.Format("[3/3]没有记录 {0}", DateTime.Now));
                return;
            }

            IsEmpty = false;
            foreach (int id in list)
            {
                var item = DAL.Snap.Get(id);
                if (item == null || item.id < 1)
                {
                    Echo(textBox, string.Format("[2/3] id:{0} 获取失败", id));
                    continue;
                }
                
                //先查看总报表是否已存在
                var itemid = PromotionReport.IsExsits(item);
                if (itemid == 0) 
                    itemid = DAL.PromotionReport.GetIncrementID();

                item.picurl = MackHTML(item, itemid);         //生成html页面

                if (!string.IsNullOrEmpty(item.picurl))
                {
                    Product.UpdateSnap(item);               //更新快照路径

                    int count = PromotionReport.InserOrUpdate(item);    //更新旧版本截图的快照路径
                    if (count < 0)
                        Echo(textBox, string.Format("[2/3]{0} 已生成,但总数未更新", item.keyword));
                    else
                        Echo(textBox, string.Format("[2/3]{0} 已生成", item.keyword));
                }
                else
                    Echo(textBox, string.Format("[2/3]{0} 生成失败", item.keyword));
            }

            Echo(textBox, "[3/3]完成");
        }

        /// <summary>
        /// 生成静态页
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        static string MackHTML(QD.Snapshot.Core.Model.Snap model, int itemid)
        {
            if (string.IsNullOrEmpty(model.html))
            {
                EchoHelper.WriteLog(string.Format("html为空,snap_id:{0},keyword:{1}", model.id, model.keyword));
                return "";
            }

            string dir = SiteConfig.HtmlPath;
            string path = string.Format("/{0}/", model.userid);
            string filePath = string.Format("{0}/{1}.html", model.userid, itemid);


            if (!string.IsNullOrEmpty(model.picurl))
            {
                if (System.IO.File.Exists(dir + model.picurl))
                    filePath = model.picurl;
            }

            string content = Template.Get(model.copyform.ToString());
            content = content.Replace("{keyword}", model.keyword);
            content = content.Replace("{list}", model.html);

            if (model.copyform == 0)
            {
                Regex r1 = new Regex("相关结果约([\\s\\S].*?)个");  //百度
                if (r1.IsMatch(model.html))
                    content = content.Replace("{num}", r1.Match(model.html).Groups[1].Value);
            }
            if (model.copyform == 2)
            {
                Regex r1 = new Regex("找到约([\\s\\S].*?)条");    //搜狗
                if (r1.IsMatch(model.html))
                    content = content.Replace("{num}", r1.Match(model.html).Groups[1].Value);
            }
            else if (model.copyform == 3)
            {
                Regex r1 = new Regex("data='([\\s\\S].*?) 条结果'");    //Bing
                if (r1.IsMatch(model.html))
                    content = content.Replace("{num}", r1.Match(model.html).Groups[1].Value);
            }
            else if (model.copyform == 4)
            {
                Regex r1 = new Regex("为您找到约([\\s\\S].*?)条相关结果"); //国搜
                if (r1.IsMatch(model.html))
                    content = content.Replace("{num}", r1.Match(model.html).Groups[1].Value);
            }
            else if (model.copyform == 5)
            {
                Regex r1 = new Regex("找到约([\\s\\S].*?)条结果");//微信
                if (r1.IsMatch(model.html))
                    content = content.Replace("{num}", r1.Match(model.html).Groups[1].Value);
                Regex r2 = new Regex("<div class='mun'>找到约([\\s\\S].*?)条结果</div>");
                if (r2.IsMatch(content))
                    content = content.Replace(r2.Match(content).Groups[0].Value, "");
            }

            try
            {
                if (!Directory.Exists(dir + path))
                    Directory.CreateDirectory(dir + path);

                using (StreamWriter sw = new StreamWriter(dir + filePath, false))
                {
                    sw.Write(content);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                filePath = "";
                EchoHelper.WriteLog(string.Format("文件生成异常:{0},path:{1}", ex.Message, filePath));
            }
            return filePath;
        }

        static void Echo(TextBox textBox, string msg)
        {
            EchoHelper.ShowMessage(textBox, msg);
        }
    }
}